#!/usr/bin/env python
#coding=utf-8
import requests
from lxml import html as H
from dateutil.parser import parse
from git import Repo
import re


def CveSearch(libname):
    """
    根据library name从cve db获得一个CVE列表
    """
    url = "https://cve.mitre.org/cgi-bin/cvekey.cgi?keyword={}".format(libname)
    text = requests.get(url).text
    dom = H.fromstring(text) 
    trs = dom.xpath("//div[@id='CenterPane']//table/tr")
    CVEs = []
    for tr in trs:
        tds= tr.xpath("td[1]")[0]
        if len(tds):
            cve = tds[0].text_content().strip()
            if cve:
                CVEs.append(cve)
    # print CVEs
    return list(set(CVEs))

def CveReportTime(CveId):
    """
    根据CVEid 从CVE db获得其被报告的时间
    """
    url = "https://cve.mitre.org/cgi-bin/cvename.cgi?name={}".format(CveId)
    text = requests.get(url).text
    dom = H.fromstring(text)
    trs = dom.xpath("//div[@id='GeneratedTable']/table//tr[9]")[0]
    createDate = trs.xpath("td[1]")[0].text_content()
    return  parse(createDate)

def ParseCommitLog(libPath):
    """
    从git repo中获取到所有commit log中包含CVE的信息
    """
    repo = Repo(libPath)
    cves = []
    previous_head = repo.active_branch
    for head in repo.branches:
        head.checkout()
        all_cve_log = repo.git.log("--grep", "CVE")
        cves.extend(re.findall(r'(CVE-\d{4}-\d+)',all_cve_log))
    previous_head.checkout()
    return list(set(cves))


